import { useRef } from 'react'
import Cubox from './ui/Cubox';
import CuboxSelect from './ui/CuboxSelect';
import CuboxSlider from './ui/CuboxSlider';
import * as colorScheme from './ui/color-scheme';
import './App.css'
import { CanvasKitProvider, useCanvasKit } from './contexts/CanvasKitContext';
import { TextRenderingProvider, useTextRendering } from './contexts/TextRenderingContext';
import { EditorProvider, useEditor } from './contexts/EditorContext';
import TextRenderer from './components/TextRenderer';

// Main editor component that uses contexts
function TextEditor() {
  const {
    canvasKitStatus,
    fontsLoaded,
    availableFonts
  } = useCanvasKit();

  const {
    fontSize,
    setFontSize,
    letterSpacing,
    selectedFont,
    setSelectedFont,
    fontVariant,
    setFontVariant,
    availableFontVariants
  } = useTextRendering();

  const {
    handleCanvasClick,
    handleKeyDown,
    handleCanvasBlur,
    isReady
  } = useEditor();

  const canvasRef = useRef(null)

  return (
    <div className="App" style={{
      display: 'flex',
      flexDirection: 'row',
      gap: '30px',
      padding: '20px',
      alignItems: 'flex-start',
      minHeight: '100vh',
      boxSizing: 'border-box'
    }}>
      {(!fontsLoaded || canvasKitStatus !== 'ready') && (
        <div style={{
          position: 'fixed',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          zIndex: 500,
          background: canvasKitStatus === 'failed' ? 'rgba(128,0,0,0.9)' : 'rgba(0,0,0,0.8)',
          color: 'white',
          padding: '20px',
          borderRadius: '8px',
          fontSize: '16px',
          fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
        }}>
          {canvasKitStatus === 'failed' ? (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span>❌</span>
                <span>CanvasKit failed to load</span>
              </div>
              <div style={{fontSize: '12px', marginTop: '10px', opacity: 0.8, textAlign: 'center'}}>
                This application requires CanvasKit to function
              </div>
            </div>
          ) : canvasKitStatus === 'loading' ? (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span>🔄</span>
                <span>Loading CanvasKit...</span>
              </div>
              <div style={{fontSize: '12px', marginTop: '10px', opacity: 0.8, textAlign: 'center'}}>
                Please wait while CanvasKit initializes
              </div>
            </div>
          ) : !fontsLoaded ? (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span>📚</span>
                <span>Loading fonts...</span>
              </div>
              <div style={{fontSize: '12px', marginTop: '10px', opacity: 0.8, textAlign: 'center'}}>
                Processing font files and creating typefaces
              </div>
            </div>
          ) : (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span>⚙️</span>
                <span>Initializing...</span>
              </div>
              <div style={{fontSize: '12px', marginTop: '10px', opacity: 0.8, textAlign: 'center'}}>
                Setting up text editor
              </div>
            </div>
          )}
          
          {/* Debug info */}
          <div style={{
            fontSize: '10px',
            marginTop: '15px',
            padding: '8px',
            background: 'rgba(255,255,255,0.1)',
            borderRadius: '4px',
            fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
            textAlign: 'left'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span>{canvasKitStatus === 'ready' ? '✅' : canvasKitStatus === 'failed' ? '❌' : '⏳'}</span>
              <span>CanvasKit</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>
              <span>{fontsLoaded ? '✅' : '⏳'}</span>
              <span>Fonts</span>
            </div>
          </div>
        </div>
      )}
      
      {/* Left Side - Canvas */}
      <div style={{ flexShrink: 0 }}>
      <Cubox 
          cornerRadius={25}
          strokeWidth={1}
          isOutlined={true}
          backColor="black"
          foreColor="white"
          hoverBackColor="black"
          hoverForeColor="white"
          style={{
        }}>
          <div style={{
            width: 550,
            height: 550,
            padding: 25,
            boxSizing: "border-box"
          }}>
            <canvas
              id="textarea"
              ref={canvasRef}
              onClick={(e) => handleCanvasClick(e, canvasRef)}
              onKeyDown={handleKeyDown}
              onBlur={handleCanvasBlur}
              tabIndex={0}
              style={{
                cursor: isReady ? 'text' : 'not-allowed',
                outline: 'none',
                imageRendering: 'pixelated',
                textRendering: 'geometricPrecision',
                opacity: isReady ? 1 : 0.6,
              }}
            />
            <TextRenderer canvasRef={canvasRef} width={500} height={500} />
            {!isReady && (
              <div style={{
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                background: 'rgba(0, 0, 0, 0.7)',
                color: 'white',
                padding: '10px 20px',
                borderRadius: '8px',
                fontSize: '14px',
                fontWeight: 'bold',
                pointerEvents: 'none'
              }}>
                Editor Loading...
              </div>
            )}
          </div>
        </Cubox>
      </div>

      {/* Right Side - Controls */}
        <Cubox 
          cornerRadius={25}
          strokeWidth={1}
          isOutlined={true}
          backColor="black"
          foreColor="white"
          hoverBackColor="black"
          hoverForeColor="white"
          style={{
          }}>
          <div style={{
            padding: '25px',
            boxSizing: "border-box",
            minWidth: '300px'
          }}>
            <h3 className="section-header">Font Settings</h3>

            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
              {/* Font Family Select */}
              <div className="form-row">
                <span className="form-label">Font Family</span>
                <div className="form-control">
                  <CuboxSelect
                  value={selectedFont}
                    suggs={availableFonts.length === 0 ? [] : availableFonts.map(font => ({
                      value: font.value,
                      desc: font.name
                    }))}
                    onChange={() => {}}
                    onSelectOption={(e, sugg) => setSelectedFont(sugg.value)}
                    placeholder={availableFonts.length === 0 ? "Loading custom fonts..." : "Select font family"}
                    color="blue"
                    style={{ width: '100%' }}
                  />
                </div>
              </div>

              {/* Font Variant Select */}
              <div className="form-row">
                <span className="form-label">Style</span>
                <div className="form-control">
                  <CuboxSelect
                  value={fontVariant}
                    suggs={availableFontVariants.map(variant => ({
                      value: variant.value,
                      desc: variant.name
                    }))}
                    onChange={() => {}}
                    onSelectOption={(e, sugg) => setFontVariant(sugg.value)}
                    placeholder="Select style"
                    color="blue"
                    style={{ width: '100%' }}
                  />
                </div>
              </div>



              <div className="form-row">
                <span className="form-label">Font Size</span>
                <div className="form-control">
                  <CuboxSlider
                    value={fontSize}
                    min={8}
                    max={64}
                    step={1}
                    onChange={(value) => setFontSize(value)}
                    color="blue"
                    valueFormatter={(val) => `${val}px`}
                  />
                </div>
                </div>


            </div>
          </div>
        </Cubox>
    </div>
  )
}

// Wrapper component that can access context states
function AppContent() {
  const { canvasKitStatus, fontsLoaded } = useCanvasKit();
  const isReady = canvasKitStatus === 'ready' && fontsLoaded;
  
  return (
    <EditorProvider isReady={isReady}>
      <TextEditor />
    </EditorProvider>
  );
}

// App wrapper with context providers
function App() {
  return (
    <CanvasKitProvider>
      <TextRenderingProvider>
        <AppContent />
      </TextRenderingProvider>
    </CanvasKitProvider>
  );
}

export default App
